package org.voice;

import java.io.*;

import javax.sound.sampled.AudioSystem;

import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.wav.WavFileReader;
import org.vosk.LogLevel;
import org.vosk.Recognizer;
import org.vosk.LibVosk;
import org.vosk.Model;

public class DecoderDemo {

    public static void main(String[] argv) throws Exception {
//        String modelPath = "D:\\model\\vosk-model-small-cn-0.22";
        String modelPath = "D:\\model\\vosk-model-cn-0.22";
        String voicePath = "D:\\FilePath\\voice\\wcj1.wav";
        File file=new File(voicePath);
        LibVosk.setLogLevel(LogLevel.DEBUG);
//        Float sampleRate = getSampleRate(file);
        Float sampleRate = 28000f;
        System.out.println("采样率: "+sampleRate);
        try (Model model = new Model(modelPath);
             InputStream ais = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(file)));
             Recognizer recognizer = new Recognizer(model, sampleRate)) {

            int nbytes;
            byte[] b = new byte[4096];
            while ((nbytes = ais.read(b)) >= 0) {
                if (recognizer.acceptWaveForm(b, nbytes)) {
                    System.out.println(">>"+recognizer.getResult());
                }
            }
            System.out.println("[]"+recognizer.getFinalResult());
        }
    }

    /**
     * 获取音频文件的采样率
     */
    private static Float getSampleRate(File file) throws Exception {
        WavFileReader fileReader = new WavFileReader();
        AudioFile audioFile = fileReader.read(file);
        String sampleRate = audioFile.getAudioHeader().getSampleRate();
        return Float.parseFloat(sampleRate);
    }

}

